package com.servlet;


import com.servlet.util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "Servletsssd",urlPatterns = {"/"})
public class Servlet extends HttpServlet {
    private Map<String,String> urlMap = new HashMap<>();
    public void init() throws ServletException {
        super.init();
        urlMap.put("list", "com.servlet.AddServlet");
        //urlMap.put("person", "com.hyl.servlet.PersonServlet");
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String dizhi = request.getRequestURI();
        String get = request.getContextPath();
        String uti = dizhi.substring(get.length()+1);
        String ut = urlMap.get(uti);
        try {
            Class utn = Class.forName(ut);
            util baseServlet = (util) utn.newInstance();
            //执行前==》设置字符编码
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=UTF-8");
            request.setCharacterEncoding("utf-8");
            //执行
            String vann = baseServlet.nn(request,response);
            nnd(vann,request,response);
        }catch (InstantiationException e) {
                e.printStackTrace();
        } catch (IllegalAccessException e) {
                e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void nnd(String xx,HttpServletRequest request, HttpServletResponse response) throws Exception {
        String x = xx.substring(xx.indexOf(':')+1);
        if(xx.startsWith("dispatcher")){
            request.getRequestDispatcher(x).forward(request,response);//转发
        }else if(xx.startsWith("redirect")){
            response.sendRedirect(x); //重定向
        }else if(xx.startsWith("out")) {
            String msg = xx.substring(xx.indexOf(':')+1);
            PrintWriter out = response.getWriter();
            out.print(msg);
            out.close();
        }else{
            throw new Exception("响应的结果异常");
        }
    }
}
